package com.sgb.kjwl.view.ui.activity.pick;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.view.View;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OneKeyLoginListener;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityPickCompanyDetailBinding;
import com.sgb.kjwl.di.pick.DaggerPickProjectComponent;
import com.sgb.kjwl.di.pick.PickProjectModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.model.entity.user.PickCompanyEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.pick.PickBidListFragment;
import com.sgb.kjwl.view.ui.fragment.pick.PickPickingListFragment;
import com.sgb.kjwl.view.ui.fragment.pick.PickProjectListFragment;
import com.sgb.kjwl.viewmodel.pick.PickCompanyDetailModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 招采企业-企业详情
 */
public class PickCompanyDetailActivity extends AppActivity {
    private ActivityPickCompanyDetailBinding binding;
    @Inject
    PickCompanyDetailModel viewModel;

    private String[] titles = {"项目列表", "招标中心", "竞价采购"};
    private SlidingFragmentPagerAdapter pagerAdapter;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private String id;
    private String phone = "";
    private String lat = "";
    private String lag = "";
    private PickCompanyEntity pickCompanyEntity;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPickProjectComponent.builder().appComponent(appComponent).pickProjectModule(new PickProjectModule(this)).build().inject(this);
    }

    public static void start(Context context, String id) {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.setClass(context, PickCompanyDetailActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        id = getIntent().getStringExtra("id");

        binding = DataBindingUtil.setContentView(PickCompanyDetailActivity.this, R.layout.activity_pick_company_detail);
        binding.setViewModel(viewModel);
//        binding.titleView.setText("企业详情");
        binding.ivBack.setOnClickListener(this);
        binding.layoutNum.setOnClickListener(this);
        binding.layoutBiding.setOnClickListener(this);
        binding.layoutBid.setOnClickListener(this);
        binding.pickLocationMap.setOnClickListener(this);
        binding.detailTel.setOnClickListener(this);
        binding.imgGz.setOnClickListener(this);
    }

    @Override
    protected void init() {
        viewModel.getCompanyData(id);
    }

    public void showCompanyData(PickCompanyEntity pickCompanyEntity) {
        this.pickCompanyEntity = pickCompanyEntity;
//        binding.tvName.setText(pickCompanyEntity.getCompanyName());
        if (pickCompanyEntity.getCompanyName().length() <= 15) {
            binding.titleView.setText(pickCompanyEntity.getCompanyName());
        } else {
            binding.titleView.setText(pickCompanyEntity.getCompanyName().substring(0, 12) + "...");
        }
        if (pickCompanyEntity.isConcernEnterprises()) {
            binding.imgGz.setImageDrawable(getResources().getDrawable(R.mipmap.icn_gz));
        } else {
            binding.imgGz.setImageDrawable(getResources().getDrawable(R.mipmap.icn_qxgz));
        }
        binding.tvName.setText(pickCompanyEntity.getCompanyName());
        binding.tvAddress.setText(pickCompanyEntity.getAddress());
        binding.tvProjectNum.setText(pickCompanyEntity.getProjNum() + "");
        binding.tvPrice.setText(pickCompanyEntity.getTotalPrice());
        binding.tvBid.setText(pickCompanyEntity.getBidNum());
        binding.tvBiding.setText(pickCompanyEntity.getTenderNum());

        if (TextUtils.isEmpty(pickCompanyEntity.getContacts())) {
            binding.layoutContact.setVisibility(View.GONE);
            binding.layoutContactTel.setVisibility(View.GONE);
        } else {
            binding.detailTel.setText(pickCompanyEntity.getContactsTel());
            binding.tvContact.setText(pickCompanyEntity.getContacts());
            binding.layoutContact.setVisibility(View.VISIBLE);
            binding.layoutContactTel.setVisibility(View.VISIBLE);
            phone = pickCompanyEntity.getContactsTel();
        }

        if (!TextUtils.isEmpty(pickCompanyEntity.getLatitude())) {
            lat = pickCompanyEntity.getLatitude();
            lag = pickCompanyEntity.getLongitude();
            binding.pickLocationMap.setVisibility(View.VISIBLE);
        }

        mFragments.add(PickProjectListFragment.newInstance(id));
        mFragments.add(PickPickingListFragment.newInstance(id));
        mFragments.add(PickBidListFragment.newInstance(pickCompanyEntity.getCompanyName()));

        pagerAdapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, titles);
        binding.viewpager.setAdapter(pagerAdapter);
        binding.viewpager.setOffscreenPageLimit(3);
        binding.tabLayout.setupWithViewPager(binding.viewpager);
    }

    public void setIsGz(boolean isGz) {
        if (isGz) {
            binding.imgGz.setImageDrawable(getResources().getDrawable(R.mipmap.icn_qxgz));
            pickCompanyEntity.setConcernEnterprises(false);
            MToast.showToast(this,"取消关注");
        } else {
            binding.imgGz.setImageDrawable(getResources().getDrawable(R.mipmap.icn_gz));
            pickCompanyEntity.setConcernEnterprises(true);
            MToast.showToast(this,"关注成功");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.layout_bid:
                binding.viewpager.setCurrentItem(2);
                break;
            case R.id.layout_biding:
                binding.viewpager.setCurrentItem(1);
                break;
            case R.id.layout_num:
                binding.viewpager.setCurrentItem(0);
                break;
            case R.id.detail_tel:
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + phone);
                intent.setData(data);
                startActivity(intent);
                break;
            case R.id.pick_location_map:
                PickCompanyLocationMapActivity.start(PickCompanyDetailActivity.this, lat, lag,pickCompanyEntity.getAddress(),pickCompanyEntity.getCompanyName());
                break;
            case R.id.img_gz:
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    jumpLogin();
                } else {
                    viewModel.checkToken("1");
                }
                break;
        }
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(PickCompanyDetailActivity.this).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(PickCompanyDetailActivity.this, EventConstant.EVENT_PICK_COMPANY_DETAIL_JUMP);
        }
    }

    //闪验
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(this));
        //开始拉取授权页
        DialogHelper.showProgressDialog(this, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code != 1000) {
                    VerificationCodeLoginActivity.start(PickCompanyDetailActivity.this, EventConstant.EVENT_PICK_COMPANY_DETAIL_JUMP);
                }
            }
        }, new OneKeyLoginListener() {
            @Override
            public void getOneKeyLoginStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code == 1000) {
                    OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                    oneKeyLoginEntity.setPlateform("Android");
                    viewModel.oneKeyLogin(oneKeyLoginEntity);
                }
            }
        });
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_PICK_COMPANY_DETAIL_JUMP);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void checkAddTokenView() {
        viewModel.userFocus(id, pickCompanyEntity.isConcernEnterprises());
    }

    public void checkTokenView() {
        Intent intent = new Intent();
        intent.putExtra("showPage", "FRAGMENT_SHOPPING");
        MainActivity.start(PickCompanyDetailActivity.this, intent);

    }

    public void toLogin() {
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, "");
        MToast.showToast(this, "登录失效，请重新登录");
        //LoginActivity.start(this);
        jumpLogin();
    }

}
